package com.myblog.controller;

import com.myblog.common.ResultInfoFactory;
import com.myblog.model.po.Category;
import com.myblog.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 
 * @since 2022-09-04
 */
@Controller
@RequestMapping("/category")
public class CategoryController {

    private static final String HTML_PREFIX="admin/category/";

    @Autowired
    private CategoryService categoryService;

    @GetMapping(value = {"/",""})
    public String category(){
        return HTML_PREFIX+"category-list";
    }

    @PreAuthorize("hasAuthority('sys:category:list')")
    @ResponseBody
    @PostMapping("/list")
    public ResultInfoFactory list(){
        List<Category> list = categoryService.list();
        return ResultInfoFactory.success(list);
    }


    @PreAuthorize("hasAnyAuthority('sys:category:add','sys:category:edit')")
    @GetMapping(value = {"/form","/form/{id}"})
    public String form(@PathVariable(required = false)Long id, Model model){
        if(id==null){
            model.addAttribute("category",new Category());
        }else {
            Category category = categoryService.getById(id);
            Category categoryParent = categoryService.getById(category.getPid());
            if(categoryParent!=null){
                category.setParentName(categoryParent.getName());
            }
            model.addAttribute("category",category);
        }
        return HTML_PREFIX+"category-form";
    }
    @PreAuthorize("hasAnyAuthority('sys:category:add','sys:category:edit')")
    @RequestMapping(value = {"/saveOrUpdate"},method = {RequestMethod.POST,RequestMethod.PUT})
    public String saveOrUpdate(Category category){
        //log.info(sysRole.toString());
        categoryService.saveOrUpdate(category);
        return "redirect:/category";
    }

    @PreAuthorize("hasAuthority('sys:category:delete')")
    @DeleteMapping("/{id}")
    @ResponseBody
    public ResultInfoFactory deleteById(@PathVariable("id") Long id){
        categoryService.removeById(id);
        return ResultInfoFactory.success();
    }

}
